package com.iuhao.orange.properties;

import com.iuhao.orange.RedisConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by yanhao
 */
@Component
@ConfigurationProperties
public class RedisProperties implements InitializingBean {

    private static final Logger lg = LoggerFactory.getLogger(RedisConfiguration.class);

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;

    public static String redis_host;
    public static String redis_password;
    public static int redis_port;
    public static int redis_database;
    public static int redis_timeout;
    public static int redis_maxIdle;
    public static long redis_maxWaitMillis;

    @Override
    public void afterPropertiesSet() throws Exception {
        redis_host = host;
        redis_password = password;
        redis_port = port;
        redis_database = database;
        redis_timeout = timeout;
        redis_maxIdle = maxIdle;
        redis_maxWaitMillis = maxWaitMillis;
    }

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        lg.info("Create JedisConnectionFactory successful");
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redis_host);
        factory.setPort(redis_port);
        factory.setTimeout(redis_timeout);
        factory.setPassword(redis_password);
        factory.setDatabase(redis_database);
        return factory;
    }

    @Bean
    public JedisPool redisPoolFactory() {
        lg.info("JedisPool init successful，host -> [{}]；port -> [{}]", redis_host, redis_port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redis_maxIdle);
        jedisPoolConfig.setMaxWaitMillis(redis_maxWaitMillis);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, redis_host, redis_port, redis_timeout, redis_password, redis_database);
        return jedisPool;
    }
}
